package com.funo.ehealth.service;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.funo.ehealth.bean.UserOrder;
import com.funo.ehealth.bean.UserUpDown;
import com.funo.ehealth.dao.UserOrderDao;
import com.funo.ehealth.dao.UserUpDownDao;
import com.funo.ehealth.util.HttpUtil;
import com.funo.ehealth.util.LogUtil;
import com.funo.ehealth.util.StringUtil;
import com.funo.ehealth.util.XmlUtil;

/** 
 * CPService类
 * 
 * @version V1.1
 * @author zhangguangying
 * @date 2012-11-16
 */
public class CPService {
	
	/**
	 * CPService日志记录器
	 */
	private static final Log log = LogFactory.getLog(CPService.class);
	
	/**
	 * 将用户订购关系同步到CP端
	 * @param userOrder 用户订购关系实体类对象
	 */
	public void sendOrderToCp(UserOrder userOrder) {
		StringBuilder respXml = new StringBuilder();
		UserOrderDao userOrderDao = new UserOrderDao();
		String reqXml = null;
		String orderurl = userOrder.getCpUserOrderUrl();//CP订购关系同步URL
		
		try {
			reqXml = StringUtil.handleString("<syncOrderRelationReq><msisdn>{}</msisdn><service_code>{}</service_code><action_code>{}</action_code><sub_msisdn>{}</sub_msisdn><sn>{}</sn></syncOrderRelationReq>",userOrder.getDestUser_ID(),userOrder.getSpServid(),userOrder.getActionID(),userOrder.getSubMsisdn(),UUID.randomUUID());
			
			HttpUtil httpUtil = new HttpUtil();
			httpUtil.connect(userOrder.getCpUserOrderUrl(),30000,30000,true,true,"POST");
			String outString = "syncOrderRelationReq="+ URLEncoder.encode(reqXml, "utf-8");
			httpUtil.output(outString);
			respXml = httpUtil.input();
			httpUtil.close();
			
			LogUtil.debug(log, "CP端订购同步响应，参数：{respXml:{}}", respXml.toString());
			String result = XmlUtil.getNodeData(respXml.toString(), "//syncOrderRelationReq//return_code");
			
			if("0".equals(result)){
				if(userOrder.getCancelFlag() == 1){
					userOrderDao.updateCpSyncFlag(0,userOrder.getId());
				}else if(userOrder.getCancelFlag() == 0){
					userOrderDao.updateCpSyncFlag(2,userOrder.getId());
				}
				LogUtil.info(log, "用户订购关系同步到CP端成功，同步内容为:{}，同步接口：{}", reqXml,orderurl);
			}else{
				LogUtil.warn(log, "用户订购关系同步到CP端失败，同步内容为:{}，同步接口：{}", reqXml,orderurl);
			}
		} catch (Exception e) {
			LogUtil.error(log, e, "用户订购关系同步到CP端异常，参数：{reqXml:{},url:{}}",reqXml,orderurl);
			// 将异常信息写入系统错误日志表
//			userOrderDao.insertErrLog(1,"同步用户订购关系到CP端异常，URL:"+orderurl);
		}
	}
	
	/**
	 * 发送上行业务交互信息给CP端
	 * @param srcterminalId 发送方号码
	 * @param destnationId 接收方号码
	 * @param serviceCmd 发送内容，已解码
	 * @param serviceurl 上行到CP的URL
	 */
	public void sendMsgToCp(UserUpDown userUpDown) {
		String reqXml = null;
		String srcterminalId = null;
		String destnationId = null;
		
		try {
			StringBuilder respXml = new StringBuilder();
			String uptime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
			String sid = "0000";
			srcterminalId = userUpDown.getSrcId();
			destnationId = userUpDown.getDestId();
			String serviceCmd = userUpDown.getContent();
			String serviceurl = userUpDown.getProductUrl();
			
			if(destnationId != null && destnationId.trim().length() == 17){
				sid = destnationId.substring(13,17);  //业务交互扩展码
			}
			//生成请求的上行到CP的XML报文
			reqXml = StringUtil.handleString("<record><tel>{}</tel><content>{}</content><uptime>{}</uptime><sid>{}</sid><sn>{}</sn></record>", srcterminalId,serviceCmd,uptime,sid,UUID.randomUUID());
			LogUtil.debug(log, "CP端业务应答请求，参数：{reqXml:{},serviceurl:{}}", reqXml,serviceurl);
		
			HttpUtil httpUtil = new HttpUtil();
			httpUtil.connect(serviceurl,20000,20000,true,true,"POST");
			String outString = "xmlrecord="+ URLEncoder.encode(reqXml, "utf-8");
			httpUtil.output(outString);
			respXml = httpUtil.input();
			httpUtil.close();
			
			LogUtil.debug(log, "CP端业务应答响应，参数：{respXml:{}}", respXml.toString());
			
			String returnCode = XmlUtil.getNodeData(respXml.toString(), "//record//return_code");
			
			if("0".equals(returnCode)){
				new UserUpDownDao().updateIsProcess(1,userUpDown.getId());
				LogUtil.info(log, "CP端业务应答成功，用户：{}，接收方号码：{}",srcterminalId,destnationId);
			}else{
				LogUtil.warn(log, "CP端业务应答失败，用户：{}，接收方号码：{}，失败信息：returnCode={}", srcterminalId,destnationId,returnCode);
			}
		} catch (Exception e) {
			LogUtil.error(log,e,"发送上行业务交互信息给CP端异常，用户：{}，接收方号码：{}，参数：reqXml:{}", srcterminalId,destnationId,reqXml);
		}
	}
	
}
